#ifndef __DBFILEBUFPAGEMANAGER_H
#define __DBFILEBUFPAGEMANAGER_H

#pragma once

#include <string>
#include <vector>
#include <map>

#include "DBFileType.h"
#include "DBFilePhyPageManager.h"

using namespace std;

const int DEFAULT_BUF_PAGE_NUM = 8192;

class DBFilePhyPageManager;

struct DBBufPageList
{
	int freeHead;
	DBBufPage pages[DEFAULT_BUF_PAGE_NUM];
};

class DBFileBufPageManager
{
private:
	int fileid;

	map<int, DBBufPage*> pid2page;

	DBFilePhyPageManager phyPageManager;

	vector<DBBufPageList*> bufPageHeadVec;

	/**
	* Funtion Description : Add a new DBBufPageList to bufPageHeadVec.
	* This can increase the buffer size
	* by Author: Jimmy
	*/
	void AllocPageList();

	/**
	* Funtion Description : Alloc a new BufPage in DBBufPageList
	* @return int
	* pid
	* by Author: Jimmy
	*/
	DBBufPage* AllocBufPage();

	/**
	* Funtion Description : Free a bufpage
	* @para int pid
	* The pid of bufpage need to be freed
	* by Author: Jimmy
	*/
	void FreeBufPage(DBBufPage* bufPage);

public:
	
	/**
	* Funtion Description :
	* Only one instance in the whole project
	* by Author: Jimmy
	*/
	DBFileBufPageManager(void);

	/**
	* Funtion Description :
	* by Author: Jimmy
	*/
	~DBFileBufPageManager(void);

	/**
	* Funtion Description : Open A file,
	* Create System table
	* @para char* filename: 
	* file name
	* @return
	* 0: open successful
	* <0: open fail
	* by Author: Jimmy
	*/
	int DBFileOpenFile(char* filename);

	/**
	* Funtion Description : Open A page
	* @para int pid:
	* page id
	* @return DBBufPage*
	* header of this page
	* by Author: Jimmy
	*/

	DBBufPage* DBFileOpenPage(int pid);

	/**
	* Funtion Description : Alloc a new page in currently open page
	* by Author: Jimmy
	* @para int& pid: this is a return value, which is the page id of 
	* new alloced page
	* @DBDiskPage*& diskPage: this is a return value, which is the head of 
	* new page
	*/
	void DBFileAllocPage(int& pid, DBBufPage*& bufPage);

	/**
	* Funtion Description : Delete A page(mark it unused)
	* by Author: Jimmy
	* @para int pid
	* page id
	*/
	void DBFileDeletePage(int pid);

	/**
	* Funtion Description : Close a page
	* @para int pid
	* page id
	* by Author: Jimmy
	*/
	void DBFileClosePage(int pid);

	/**
	* Funtion Description :Close the currently opened file
	* by Author: Jimmy
	*/
	void DBFileCloseFile();
};

#endif